package com.codejiwei.core.graphx

import org.apache.spark.graphx.{Edge, Graph, PartitionStrategy}
import org.apache.spark.{SparkConf, SparkContext}

object GraphX_GroupEdges {
  def main(args: Array[String]): Unit = {
    val sc = new SparkContext(new SparkConf().setMaster("local[*]").setAppName("GraphXSubgraph"))

    // 创建一个简单的图
    val vertices = sc.parallelize(Array((1L, "Alice"), (2L, "Bob"), (3L, "Charlie"), (4L, "David")))
    val edges = sc.parallelize(Array(
      Edge(1L, 2L, 3), // 边1: Alice -> Bob，权重为3
      Edge(1L, 2L, 2), // 边2: Alice -> Bob，权重为2
      Edge(1L, 3L, 1), // 边3: Alice -> Charlie，权重为1
      Edge(2L, 3L, 4), // 边4: Bob -> Charlie，权重为4
      Edge(3L, 4L, 5), // 边5: Charlie -> David，权重为5
      Edge(3L, 4L, 5)  // 边6: Charlie -> David，权重为6
    ))

    val graph: Graph[String, Int] = Graph(vertices, edges, "default")
    //TODO 图必须使用partitionBy进行分区
    val partitionedGraph = graph.partitionBy(PartitionStrategy.RandomVertexCut)

    val mergeFunction: (Int, Int) => Int = (a, b) => a + b
    val groupedGraph = partitionedGraph.groupEdges(mergeFunction)

    // 输出新图的顶点和边
    println("Vertices in grouped graph:")
    groupedGraph.vertices.collect().foreach(println)

    println("Edges in grouped graph:")
    groupedGraph.edges.collect().foreach(println)


  }
}
